import '@/assets/font/iconfont';
import cx from 'classnames';
import React from 'react';
import './index.less';

interface Props {
  /**
   * icon 名称
   */
  name: string;

  /**
   * icon 鼠标悬浮时的名称
   */
  hoverName?: string;
  /**
   * icon 大小 即fontSize, 也可以通过style属性定义
   * 二者都定义，以size为准
   */
  size?: number;

  /**
   * 定义额外的其他样式
   */
  style?: Record<string, any>;

  /**
   * 图标文字说明
   */
  title?: string;

  /**
   * 图标最外层className
   */
  wrapClassName?: string;

  /**
   * 点击事件
   */
  onClick?: (e: React.MouseEvent) => void;

  /**
   * icon附属文本
   */
  text?: string;
}

function Icon({ name, hoverName, style, size, title, wrapClassName, text, onClick }: Props) {
  const [href, setHref] = React.useState(name);
  const handleIconMouseEnter = () => {
    if (hoverName) {
      setHref(hoverName);
    }
  };

  const handleIconMouseLeave = () => {
    setHref(name);
  };

  return React.createElement(
    'div',
    {
      title,
      className: cx('icon-wrap', wrapClassName),
      onClick,
      onMouseOver: handleIconMouseEnter,
      onMouseLeave: handleIconMouseLeave,
    },
    React.createElement(
      'svg',
      {
        className: 'icon',
        'aria-hidden': true,
        style: { ...style, fontSize: size || style?.fontSize },
      },
      React.createElement('use', { xlinkHref: `#${href}` }),
    ),
    text ? React.createElement('span', null, text) : null,
  );
}

export default Icon;
